<template>
  <div class="add-create">
    <ContentWrap>
      <!-- <h2>修改报告规则</h2> -->
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-row>
          <!-- 第一行 -->
          <el-col :span="12">
            <el-form-item label="规则名称：" prop="Name">
              <el-input v-model="ruleForm.Name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报告模板：" prop="reportTemplate">
              <el-select
                v-model="ruleForm.reportTemplate"
                class="!w-360px"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in optionsList"
                  :key="item.id"
                  :label="item.reportName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 第二行 -->
          <el-col :span="16">
            <el-form-item label="最大烈度范围:">
              <el-row :gutter="5" style="width: 100%">
                <el-col :span="7">
                  <el-select
                    v-model="ruleForm.grade"
                    clearable
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in gradeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-select v-model="ruleForm.symbol" clearable placeholder="请选择">
                    <el-option
                      v-for="item in symbolList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="2" style="text-align: center">烈度</el-col>
                <el-col :span="4">
                  <el-select v-model="ruleForm.symbol2" clearable placeholder="请选择">
                    <el-option
                      v-for="item in symbolList2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="7">
                  <el-select
                    v-model="ruleForm.grade2"
                    clearable
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in gradeList2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <!-- 第三行 -->
          <el-col :span="16">
            <el-form-item label="灾区人口范围:">
              <el-row :gutter="5" style="width: 100%">
                <el-col :span="7">
                  <el-input v-model="ruleForm.disaster" style="width: 100%" placeholder="请输入" />
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="ruleForm.disasterSymbol"
                    clearable
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in disasterList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="2" style="text-align: center">人数</el-col>
                <el-col :span="4">
                  <el-select
                    v-model="ruleForm.disasterSymbol2"
                    clearable
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in disasterList2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="7"><el-input v-model="ruleForm.disaster2" style="width: 100%" placeholder="请输入" /></el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <!-- 第四行 -->
          <el-col :span="16">
            <el-form-item label="地震类型:" style="display: flex; align-items: center">
              <el-checkbox v-model="ruleForm.checked1" label="正式" size="large" />
              <el-checkbox v-model="ruleForm.checked2" label="测试" size="large" />
              <el-checkbox v-model="ruleForm.checked3" label="演练" size="large" />
              <el-checkbox v-model="ruleForm.checked4" label="自动" size="large" />
            </el-form-item>
          </el-col>
          <!-- 第五行 -->
          <el-col :span="12">
            <el-form-item label="区域外扩距离:" prop="distance">
              <el-input v-model="ruleForm.distance" style="width: 200px" placeholder="请输入" />
              <span>&emsp;千米</span>
            </el-form-item>
          </el-col>
          <!-- 第六行 -->
          <el-col :span="24">
            <el-form-item label="区域范围:" style="display: flex; align-items: center">
              <el-radio-group v-model="ruleForm.radio1">
                <el-radio value="2" size="large"  @click="provinceRef.close()">上传区域文件</el-radio>
                <el-radio value="1" size="large" @click="provinceRef.open()"
                  >按行政区划选择</el-radio
                >
              </el-radio-group>
              <ProvinceCity
                
                style="margin-top: 10px"
                ref="provinceRef"
                :regionLists="ruleForm.regionList"
                @querySelect="querySelect"
              />
            </el-form-item>
            <el-form-item
              v-if="ruleForm.radio1 == '1'"
              label=""
              style="display: flex; margin-left: 60px"
            >
              {{ regionLists }}
            </el-form-item>
            <el-form-item>
              <UploadFile
                v-show="ruleForm.radio1 == '2' ? true : false"
                v-model="ruleForm.fileList"
                :updateUrl="uploadUrl"
                @uploadSuccess="uploadSuccess"
                @removeFile="removeFile"
                :downloadFileUrl="downloadFileUrl"
                :limit="1"
              >
              </UploadFile>
            </el-form-item>
          </el-col>
          <!-- 地图区域 -->
          <div style="height: 500px">
            <div style="width: 800px; height: 500px; margin: 0 auto">
              <LoadMap :fileidInfo="fileidInfo" style="height: 100%" />
            </div>
          </div>
        </el-row>
      </el-form>
      <!-- 底部按钮 -->
      <div style="display: flex; justify-content: flex-end; margin-top: 30px">
        <el-button size="large" @click="onClose">关闭</el-button>
        <el-button type="primary" size="large" @click="onStorage">保存</el-button>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
import router from '@/router'
import * as datarApi from '@/api/report'
import UploadFile from '@/views/responseLevel/populationDensity/create/UploadFileRule2.vue'
const uploadUrl = ref(import.meta.env.VITE_BASE_URL + '/admin-api/quake/report/file/uploadShpFile')
import * as timingTrigger from '@/api/earthquake/timingTrigger'
import ProvinceCity from '@/views/responseLevel/populationDensity/create/provinceCity.vue'
const downloadFileUrl = ref(import.meta.env.VITE_BASE_URL + '/admin-api/att/downLoadFile')
import LoadMap from '@/views/earthquake/earthquakeServer/gis/LoadMap.vue'
const emit = defineEmits(['modifyCreate'])
// 接收父组件传递的数据
const props = defineProps({
  rows: {
    type: Object,
    default: {}
  }
})
// 表单数据
const ruleForm = ref({
  Name: '',
  reportTemplate: '',
  grade: '',
  symbol: '',
  symbol2: '',
  grade2: '',
  disaster: '',
  disasterSymbol: '',
  disasterSymbol2: '',
  disaster2: '',
  checked1: '',
  checked2: '',
  checked3: '',
  checked4: '',
  distance: '',
  radio1: '',
  fileNames: [],
  fileList: [],
  voList: [],
  regionList: [],
  is_update: '0'
})

const eq_typeChecked = ref('')
const formValues = ref([false, false, false, false]) // 用于存储复选框的选中状态
const regionLists = ref('')
const ruleFormRef = ref(null)
const provinceRef = ref()
const form = reactive({
  file: []
})
// 下拉列表数据
const optionsList = ref([])
// 等级
const gradeList = ref([
  { value: '4', label: 'Ⅳ度' },
  { value: '5', label: 'Ⅴ度' },
  { value: '6', label: 'Ⅵ度' },
  { value: '7', label: 'Ⅶ度' },
  { value: '8', label: 'Ⅷ度' },
  { value: '9', label: 'Ⅸ度' },
  { value: '10', label: 'Ⅹ度' }
])
// 符号
const symbolList = ref([
  { value: '<=', label: '<=' },
  { value: '<', label: '<' }
])
// 符号二
const symbolList2 = ref([
  { value: '<=', label: '<=' },
  { value: '<', label: '<' },
  { value: '=', label: '=' }
])
// 等级
const gradeList2 = ref([
  { value: '4', label: 'Ⅳ度' },
  { value: '5', label: 'Ⅴ度' },
  { value: '6', label: 'Ⅵ度' },
  { value: '7', label: 'Ⅶ度' },
  { value: '8', label: 'Ⅷ度' },
  { value: '9', label: 'Ⅸ度' },
  { value: '10', label: 'Ⅹ度' }
])
// 受灾符号1
const disasterList = ref([
  { value: '<=', label: '<=' },
  { value: '<', label: '<' }
])
// 符号二
const disasterList2 = ref([
  { value: '<=', label: '<=' },
  { value: '<', label: '<' },
  { value: '=', label: '=' }
])
// 校验
const rules = reactive({
  Name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  reportTemplate: [{ required: true, message: '请选择报告模板', trigger: 'change' }],
  distance: [{ required: true, message: '请输入距离', trigger: 'blur' }]
})

const rows = props.rows
const fileidInfo = ref({
  fileid: rows.id + '',
  type: 1,
  xzqh: [],
  query: {
    tableName: 'report_rule_shp',
    fields: 'id,province,city,full_name,create_user,create_time,del_flag,rule_id,source,code',
    filter: `rule_id=${rows.id}`
    //   owner:"private"
  }
})

// 列表数据
const getListsData = async () => {
  try {
    const response = await datarApi.getLists()
    optionsList.value = response
    console.log(optionsList.value, '123')
  } catch (error) {
    console.log('失败123')
    // 在这里处理异常
  }
}

const handleTypeChange = (val) => {
  if (!provinceRef.value) return
  if (val) provinceRef.value.open()
  else provinceRef.value.close()
}

const querySelect = (value) => {
  console.log(value, '11111')
  let data = []
  value.forEach((item) => {
    if (item.city) {
      data.push(item.province + '-' + item.city)
    } else {
      data.push(item.province)
    }
  })
  regionLists.value = data.join(',')
  // ruleForm.value.regionList = value //data.join(',');
  ruleForm.value.regionList = value
  console.log(value, '1111')
  ruleForm.value.is_update = 2
  // console.log(regionLists.value,'1111');
  // ruleForm.value.regionList = value //data.join(',');
  // ruleForm.regionList = data
  cityList()
}

const cityList = async () => {
  let citydatas = {
    city: regionLists.value,
    type: ''
  }
  try {
    const response = await datarApi.postCityList(citydatas)
    console.log(response, '11111111')
    fileidInfo.value.type = 0 //改变fileid回显区域
    fileidInfo.value.query.tableName = 'temp_file_data' //改变fileid回显区域
    fileidInfo.value.query.fields = 'id' //改变fileid回显区域
    fileidInfo.value.fileid = response.id //改变fileid回显区域
    delete fileidInfo.value.query.filter
  } catch (error) {
    console.error('请求后端API时发生错误:', error)
  }
}

const querySelect1 = (value) => {
  ruleForm.value.regionList = value
  let data = []
  value.forEach((item) => {
    if (item.city == '') {
      data.push(item.province)
    } else {
      console.log(111111111)
      data.push(item.province + '-' + item.city)
    }
  })
  return data.join(',')
  // console.log(regionLists.value,'1111');
  // ruleForm.value.regionList = value //data.join(',');
  // ruleForm.regionList = data
}

// 上传成功
const uploadSuccess = (file) => {
  console.log(file)
  ruleForm.value.voList.push(file[0])
  ruleForm.value.is_update = 1
  fileidInfo.value.type = 0 //改变fileid回显区域
  fileidInfo.value.query.tableName = 'temp_file_data' //改变fileid回显区域
  fileidInfo.value.query.fields = 'id' //改变fileid回显区域
  delete fileidInfo.value.query.filter
  fileidInfo.value.fileid = file[0].ID //改变fileid回显区域
}

// 删除文件
const removeFile = (file) => {
  ruleForm.value.voList = ''
  console.log(file.attachId)
  timingTrigger.deleteFile(file.attachId)
  fileidInfo.value.fileid = '' //改变fileid回显区域
}

// 保存
const onStorage = async () => {
  // getdigit()
  let selectedValues = []
  if (ruleForm.value.checked1 === true) {
    selectedValues.push('1')
  }
  if (ruleForm.value.checked2 === true) {
    selectedValues.push('2')
  }
  if (ruleForm.value.checked3 === true) {
    selectedValues.push('3')
  }
  if (ruleForm.value.checked4 === true) {
    selectedValues.push('4')
  }
  eq_typeChecked.value = selectedValues.join(',') // 用逗号连接
  const valid = await ruleFormRef.value.validate()
  if (ruleForm.value.is_update == 1) {
    ruleForm.value.regionList = []
  }
  try {
    if (valid) {
      let row = props.rows
      let pageList = {
        id: row.id,
        name: ruleForm.value.Name,
        templateId: ruleForm.value.reportTemplate,
        intensityStat: findGradeLabel1(ruleForm.value.grade),
        intensityStatType: ruleForm.value.symbol,
        intensityEnd: findGradeLabel1(ruleForm.value.grade2),
        intensityEndType: ruleForm.value.symbol2,
        populationStat: ruleForm.value.disaster,
        populationStatType: ruleForm.value.disasterSymbol,
        populationEnd: ruleForm.value.disaster2,
        populationEndType: ruleForm.value.disasterSymbol2,
        regionExtendDistance: ruleForm.value.distance,
        eqType: eq_typeChecked.value,
        voList: ruleForm.value.voList,
        regionList: ruleForm.value.regionList,
        is_update: ruleForm.value.is_update,
        scope: row.scope,
        ruleFileId: row.ruleFileId
      }
      console.log(pageList, '------')
      const response = await datarApi.update(pageList)
      if (response) {
        let addflag = true
        emit('modifyCreate', addflag)
        // router.push({ path: '/produce/produce/report' })
      }
    }
  } catch (error) {
    console.log('失败123')
  }
}
// 关闭
const onClose = () => {
  // router.push({ path: '/produce/produce/report' })
  let addflag = true
  emit('modifyCreate', addflag)
}

const initwxMap = () => {
  var map
  var zoom = 12
  // var geocode;
  map = new T.Map('mapDiv')
  // 坐标
  map.centerAndZoom(new T.LngLat(116.40769, 39.89945), zoom)
  //创建对象
  // geocode = new T.Geocoder();
  // 地图类型
  map.setMapType(TMAP_HYBRID_MAP)
}

const getrow = () => {
  let row = props.rows
  ruleForm.value.Name = row.name
  ruleForm.value.reportTemplate = row.templateId
  ruleForm.value.grade = findGradeLabel(row.intensityStat)
  ruleForm.value.symbol = row.intensityStatType
  ruleForm.value.grade2 = findGradeLabel(row.intensityEnd)
  ruleForm.value.symbol2 = row.intensityEndType
  ruleForm.value.disaster = row.populationStat
  ruleForm.value.disasterSymbol = row.populationStatType
  ruleForm.value.disaster2 = row.populationEnd
  ruleForm.value.disasterSymbol2 = row.populationEndType
  eq_typeChecked.value = gettrue(row.eqType)
  ruleForm.value.distance = row.regionExtendDistance
  if (row.voList !== null) {
    ruleForm.value.fileList.push({ name: row.voList[0].fileName, url: row.voList[0].path })
  }
  if (row.regionList !== null) {
    regionLists.value = querySelect1(row.regionList)
  }
  // console.log(ruleForm.value,'-----');
}
const findGradeLabel = (value) => {
  const grade = gradeList.value.find((grade) => grade.value == value)
  return grade ? grade.label : ''
}
const findGradeLabel1 = (label) => {
  if (!isNaN(Number(label))) {
    return label
  }
  const grade = gradeList.value.find((grade) => grade.label === label)
  return grade ? grade.value : ''
}

const gettrue = (value) => {
  if (value !== null) {
    const valueString = value.toString()
    // 将字符串转换为数组，每个字符作为一个元素
    const valuesArray = valueString.split('')

    // 将数组中的元素转换为字符串，并打印结果
    const result = valuesArray.map((digit) => digit.toString())
    result.forEach((item) => {
      if (item == 1) {
        ruleForm.value.checked1 = true
      }
      if (item == 2) {
        ruleForm.value.checked2 = true
      }
      if (item == 3) {
        ruleForm.value.checked3 = true
      }
      if (item == 4) {
        ruleForm.value.checked4 = true
      }
    })
  }
}

// const getdigit = () => {
//     let row = JSON.parse(route.query.rows);
//     ruleForm.value.grade = row.intensityStat
//     ruleForm.value.grade2 = row.intensityEnd
// }

const getscope = () => {
  let row = props.rows
  ruleForm.value.radio1 = row.scope.toString()
  console.log(ruleForm.value.radio1, '+++++++++')
}
onMounted(() => {
  // initwxMap()
  getListsData()
  getrow()
  getscope()
})
</script>

<style scoped> 
.add-create {
  /* background-color: #f0f2f5; */
  /* padding: 20px; */
}
</style>
